<?php

namespace App\Http\Controllers\Admin;

use Laravel\Lumen\Routing\Controller as BaseController;

class Controller extends BaseController
{

    // 更新字段若为空值则排除掉，不更新
    protected function unsetEmptyFields($inputs, $fields)
    {
        foreach ($fields as $field) {
            if (empty($inputs[$field])) {
                unset($inputs[$field]);
            }
        }
        return $inputs;
    }

    // 更新时允许字段为空
    protected function allowNullRules($rules)
    {
        foreach ($rules as &$rule) {
            $rule = preg_replace('/required/', 'nullable', $rule);
        }
        return $rules;
    }

    // 获取请求的顺序语句
    protected function getOrderByQuery($allowFields = [])
    {
        $request = app()->request;
        $sort = $request->get('sort');

        if ($sort) {
            $order = $sort[0] ?? 'desc';
            $orderField = substr($sort, 1) ?? 'id';

            if (in_array($orderField, $allowFields)) {
                return $orderField . ' ' . ($order == '+' ? ' asc' : 'desc');
            }
        }
        return 'id desc';
    }

    // 获取过滤条件
    protected function getFilterConditions($fields = [])
    {
        $filters = [];
        if ($fields) {
            $request = app()->request;
            foreach ($fields as $fieldName) {
                if ($value = $request->get($fieldName)) {
                    $filters[$fieldName] = $value;
                }
            }
        }
        return $filters;
    }

}
